from flask import g, current_app
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.utils.decorators import login_required
from comment.modules.user import User
from comment.modules.debt_info import Debt_info
from comment.modules import db
from financial.resources.transaction.serializer import DebtPaginateSerializer


class Debt(Resource):

    def get(self):
        """管理员查询所有的债权列表"""
        rp = RequestParser()
        rp.add_argument('start')  # 开始时间
        rp.add_argument('end')  # 结束时间
        rp.add_argument('curPage')  # 当前页
        rp.add_argument('perPage')  # 每页数量

        args = rp.parse_args()
        start = args.get('start')
        end = args.get('end')
        cur_page = int(args.get('curPage'))
        per_page = int(args.get('perPage'))

        # 过滤查询
        debt_list = Debt_info.query

        # 第一个过滤条件，根据时间
        if start and end:
            # 需要根据起始和结束的时间过滤
            debt_list = debt_list.filter(db.cast(Debt_info.loanStartDate, db.DATE) >= db.cast(start, db.DATE)) \
                .filter(db.cast(Debt_info.loanStartDate, db.DATE) <= db.cast(end, db.DATE)) \
                .paginate(cur_page, per_page, error_out=False)
        else:
            debt_list = debt_list.paginate(cur_page, per_page, error_out=False)

        # 分页数据的序列化
        data = DebtPaginateSerializer(debt_list).to_dict()

        return {'msg': 'success', 'data': data}
